const { uploadDir, readData, pushLog } = require('../common/operate');
var { APIError } = require('../common/status');
const send = require('koa-send');
var fs = require('fs');
var path = require('path');

var fn_download = async (ctx, next) => {
    let token = ctx.headers.mytoken || false
    if (readData(ctx.params.id) == token) {
        if (ctx.params.id && ctx.params.time && ctx.params.name) {
            let root = path.join(uploadDir, `/${ctx.params.id}/${ctx.params.time}`)
            let filePath = path.join(root, `${ctx.params.name}`)
            try {
                let stats = fs.statSync(filePath)
                if (stats.isFile()) {
                    let fileName = `${ctx.params.name}`
                    ctx.attachment(fileName);
                    pushLog(ctx.params.id, ctx.params.time, ctx.params.name, '下载文件', '成功')
                    await send(ctx, fileName, { root });
                }
            } catch (e) {
                pushLog(ctx.params.id, ctx.params.time, ctx.params.name, '下载文件', '失败')
                APIError(ctx, 404, '下载失败')
            }
        } else {
            APIError(ctx, 400, '参数错误')
        }
    } else {
        pushLog(ctx.params.id, ctx.params.time, ctx.params.name, '下载文件', '权限不通过')
        APIError(ctx, 403, '权限不通过')
    }
}

module.exports = fn_download